package logic

import (
	"baidu/baidurpc/baidurpc"
	"baidu/baidurpc/internal/svc"
	"baidu/modil/cache"
	"baidu/modil/mysql"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"time"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *baidurpc.RegisterRequest) (*baidurpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	get := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}
	mobile := in.Mobile
	cache.Rdb.Set(l.ctx, "mobile", mobile, time.Hour)
	cmd, _ := cache.Rdb.Get(l.ctx, "mobile").Int()
	if cmd >= 2 {
		return nil, fmt.Errorf("一个手机号只能注册一次")
	}
	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Mobile).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("该用户已存在,请前去登录")
	}
	m := mysql.User{
		Account:  in.Account,
		Password: in.Password,
	}
	mysql.DB.Debug().Create(&m)
	return &baidurpc.RegisterResponse{
		UserId: int64(m.ID),
	}, nil
}
